const app = getApp();

app.func.skulist({

    /**
     * 页面的初始数据
     */
    data: {
        cardid: '',
        sku: [],
        skuid: '',
        productlist: {},
        categorylist: '',
        thispNum: '',
        pageEnd: false,
        bottom_tap: false,
        selectBox:false,
        currentTab: 1,
        type: null,   //1推荐   2价格   3折扣
        addproindex: '',
        disabled: [],
        selected: {},
        selectedcount: 0,
        maxcount: 0,
        showbox: false,
        chooseindex: 2,
        id: 0,
        key: '',
        min: null,
        max: null,
        sort: '',
        minprice:0,
        maxprice:-1,
        showPriceArea:false,
        brandid:[]
    },

    /**
     * 生命周期函数--监听页面加载   url: "/pages/about/cs/cs?id=null&length=&maxcount=" + left + "&ids=" + ids.join(",")
     */
    onLoad: function (options) {
        this.supplierList();
        if(options.maxp > 0){
            this.setData({
                minprice:options.minp,
                maxprice:options.maxp
            })
        }else{
            this.setData({ showPriceArea:true });
        }
        if (options.length) {
            this.setData({addproindex: options.length});
        }
        if (options.ids) {
            var ids = options.ids.split(',');
            this.setData({disabled: ids});
        }
        if (options.brandid) {
            this.setData({brandid:  JSON.parse(options.brandid)});
        }
        this.eventChannel = this.getOpenerEventChannel();
        this.setData({cardid: options.id, maxcount: options.maxcount});

        app.func.getPromise('/categories')
            .then(([code, res]) => {
                if (code == 200) {
                    this.setData({
                        categorylist: res.data,
                    }, this.requestnav(0, 2, 0, 10000));
                }
            })
    },


    requestnav: function (id, type, min, max) {
        let tabindex = 'sku' + id;
        this.setData({
            skuid: tabindex,
            id: id,
        });
        if (id >= 0) {
            this.getBrandlist(id);
        }
        let result = this.packageJson({id: id, type: type, min: min, max: max});
        this.reqpropuct1(result);
    },
    reqpropuct1: function (obj) {
        app.func.postPromise('/card/selectpro2', obj).then(([code, res]) => {
            if (obj.offset == 0) {
                if(res.data.length == 0){
                    app.func.toastPromise('没有符合该条件的商品');
                    return;
                }
                this.getauthids(res.data,(codes,data)=>{
                    this.setProductList(res.data, obj.id,data.data);
                });
            } else if (res.data.length == 0) {
                this.setProductListEnd(obj.id, () => wx.hideLoading());
            } else {
                if (res.data.length < 20) {
                    this.setProductListEnd(obj.id, () => wx.hideLoading());
                }
                this.getauthids(res.data,(codes,data)=>{
                    this.addProductList(res.data, obj.id, () => wx.hideLoading(),data.data);
                });
            }
        })
    },

    getauthids(arr, cd) {
        let proid = arr.map(item => item.id).toString();
        let brandid =  this.data.brandid.toString();
        app.func.postPromise(`/brand/certificate`, {
            proid: proid,
            brandid: brandid
        }).then(([code,res]) => {
            cd(code,res);
        })
    },


    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        var list = this.data.productlist[this.data.skuid];
        var data = this.data;
        if (list.pageEnd) {
            //do nothing
        } else if (this.data.id == 999) {
            wx.showLoading({title: '加载更多', mask: true});
            this.optimalList(data.id, list.data.length);
        } else {
            wx.showLoading({title: '加载更多', mask: true});
            let result = this.packageJson({
                id: data.id, type: list.type, min: data.min, max: data.max, offset: list.data.length,
                minrate: data.minrate, maxrate: data.maxrate, key: data.key, sort: data.sort,sup_id:data.sup_id,
                brand: data.brand,
            });
            this.reqpropuct1(result);
        }
    },


    requestnav1: function (result) {
        this.reqpropuct1(result);
    },


    //处理需要提交的数据
    packageJson:function(obj){
        // let id = obj.id ? obj.id : 0;
        let id = obj.id === 0 || obj.id ? obj.id : this.data.id;
        let key = obj.key || '';
        let sort = obj.sort || '';
        let type = obj.type || 2;
        let offset = obj.offset || 0;
        let minrate = obj.minrate || '';
        let maxrate = obj.maxrate || '';
        let sup_id = obj.sup_id || '';
        let brand = obj.brand || '';

        let min;
        let max;
        if(obj.minprice){
            min = obj.minprice;
            max = obj.maxprice;
        }else if(this.data.maxprice >0){
            min = this.data.minprice;
            max = this.data.maxprice;
        }else{
            min = 0;
            max = 10000;
        }
        let result = {
            id: id,
            offset: offset,
            type: type,
            key: key,
            min: min,
            max: max,
            min_rate: minrate,
            max_rate: maxrate,
            sort: sort,
            length: 20,
            sup_id:sup_id,
            brand:brand
        };
        this.setData({
            id: id, type: type, min: min, max: max,sup_id:sup_id,
            key: key, sort: sort, minrate: minrate, maxrate: maxrate,
            brand:brand,
        });

        return result;
    },


    //点击 推荐
    choosetype: function (e) {
        this.scrollTop();
        let id = this.data.id;
        let data = this.data;
        let type = e.currentTarget.dataset.type;
        this.setData({ selectBox: false });

        let result = this.packageJson({
            brand:this.data.brand,
            sup_id:data.sup_id,
            id: id,
            type: type,
            key: data.key,

        });
        this.reqpropuct1(result)
    },






    //点击 价格/折扣排序
    proListOrder: function (e) {
        this.scrollTop();
        let ordetType = e.currentTarget.dataset.type;
        let sort = this.data.sort;
        let data = this.data;
        if (ordetType == 0) {
            sort = sort && sort == 3 ? 4 : 3;
        } else {
            sort = sort && sort == 1 ? 2 : 1;
        }
        let result =  this.packageJson({
            id: data.id, minrate: data.minrate, maxrate: data.maxrate,
            key: data.key, sort: sort, type: data.type,sup_id:data.sup_id,
            brand:data.brand,
        });
        this.reqpropuct1(result);
    },

    //点击筛选
    chooseall: function () {
        this.companyInfoInit();
        this.setData({selectBox: true, chooseindex: 2, showbox: true});
    },
    backbtn: function () {
        this.setData({showbox: false,selectBox: false});
    },



    formsubmit(e) {
        let id = this.data.id;
        let type = this.data.chooseindex;
        let minrate = e.detail.value.minrate;
        let maxrate = e.detail.value.maxrate;
        let minprice = e.detail.value.minprice;
        let maxprice = e.detail.value.maxprice;
        let key = e.detail.value.key;
        let sup_id =  e.detail.value.company== null ? '' : this.data.company[e.detail.value.company].id;
        let brand = this.data.brand;

        if(minprice.length == 0 && maxprice.length ==0){
            this.setData({
                showbox: false
            }, ()=>{
                let result = this.packageJson({
                    id: id, type: type, minrate: minrate, maxrate: maxrate, key: key, sup_id: sup_id,
                    brand:brand
                });
                this.reqpropuct1(result);
            });
        }else{
            if(minprice < 0 || minprice.length == 0){
                app.func.toastPromise('最小价格不符合规范');
                return;
            }
            if(maxprice < 0 || maxprice.length == 0){
                app.func.toastPromise('最大价格不符合规范');
                return;
            }
            if(parseInt(maxprice) < parseInt(minprice)){
                app.func.toastPromise('最大价格不能小于最小价格');
                return;
            }
            this.setData({
                    minprice: minprice, maxprice: maxprice, showbox: false
                },
                () => {
                    let result = this.packageJson({
                        id: id, type: type, minprice: minprice, maxprice: maxprice, sup_id: sup_id,
                        minrate: minrate, maxrate: maxrate, key: key,brand:brand
                    });
                    this.reqpropuct1(result);
                });
        }
    },

    //获取所选择的ID
    getSelectedIds: function (id) {
        let infos = this.data.selected;
        let keys = Object.keys(infos);
        let ids = [];
        for (var i = 0; i < keys.length; i++) {
            ids.push(infos[keys[i]].id);
        }
        return ids;
    },




    preRequestCheckid:function(e){
        if (e.target.dataset.id == -1) {
            this.optimal(999);
        } else {
            this.requestnav(e.target.dataset.id, 2, 0, 10000);
        }
    },


    DataType(tgt, type) {
        const dataType = Object.prototype.toString.call(tgt).replace(/\[object (\w+)\]/, "$1").toLowerCase();
        return type ? dataType === type : dataType;
    },
    dealAuthProduct(authProducts,product) {
        if (this.DataType(authProducts) == "array") {
            let result = authProducts.filter(ele => ele.pro_id == product.id);
            result.length == 0 ? product.brandinfo = false : product.brandinfo = result[0];
        } else {
            product.brandinfo = false;
        }
    },

    //处理 第一次加载商品（点击顶部，或者其他筛选条件）的数据
    setProductList: function (list, id, authProducts) {
        if (list != null) {
            for (let i = 0; i < list.length; i++) {
                let product = list[i];
                this.dealAuthProduct(authProducts,product);
                if (this.data.disabled.indexOf(product.id + "") >= 0) {
                    product.checked = true;
                    product.disabled = true;
                } else {
                    if (this.data.selected["product" + product.id] != null) {
                        product.checked = true;
                    }
                }
            }
        }
        var toset = "productlist.sku" + id;
        this.setData({
            [toset]: {data: list, pageEnd: false}
        });
    },
    //处理 触底加载，加载更多商品 的数据
    addProductList: function (list, id, cb, authProducts) {
        let productlist = this.data.productlist['sku' + id].data;
        let resultlist = productlist.concat(list);
        for (let i = 0; i < resultlist.length; i++) {
            let product = resultlist[i];
            this.dealAuthProduct(authProducts,product);
            if (this.data.disabled.indexOf(product.id + "") >= 0) {
                product.checked = true;
                product.disabled = true;
            } else {
                if (this.data.selected["product" + product.id] != null) {
                    product.checked = true;
                }
            }
        }
        this.setData({
            ["productlist.sku" + id + ".data"]: resultlist
        }, cb);
    },
    //处理 触底，商品加载完成 提示："已经到底了"
    setProductListEnd: function (id, cb) {
        var toset = "productlist.sku" + id + ".pageEnd";
        this.setData({
            [toset]: true
        }, cb);
    },
    //处理 优选 的数据
    optimal: function (id) {
        var productlist = this.data.productlist;
        var tabindex = 'sku' + id;
        this.setData({
            skuid: tabindex,
            id: id,
        });
        if (!productlist[tabindex]) {
            this.optimalList(999, 0);
        } else {
            var products = this.data.productlist[tabindex].data;
            var ids = this.getSelectedIds();
            for (var i = 0; i < products.length; i++) {
                let product = products[i];
                if (!product.disabled) {
                    if (ids.indexOf(product.id) >= 0) {
                        product.checked = true;
                    } else {
                        product.checked = false;
                    }
                }
            }
            this.setData({
                ["productlist." + tabindex + ".data"]: products
            });
        }
    },
    optimalList: function (id, offset) {
        app.func.getPromise('/product/choose2/' + offset + '?length=5')
            .then(([code, res]) => {
                if (offset == 0) {
                    this.getauthids(res.data,(codes,data)=>{
                        this.setProductList(res.data, id,data.data);
                    });
                } else if (res.data.length == 0) {
                    this.setProductListEnd(id, () => wx.hideLoading());
                } else {
                    if (res.data.length < 5) {
                        this.getauthids(res.data,(codes,data)=>{
                            this.setProductListEnd(id, () => wx.hideLoading(),data.data);
                        });
                    }
                    this.addProductList(res.data, id, () => wx.hideLoading());
                }
            })
    },


    //点击复选框
    checkboxChange: function (e) {
        let tabindex = this.data.skuid;
        let list = this.data.productlist[tabindex].data;
        let checked = e.detail.value;
        let selected = this.data.selected;
        for (let i = 0; i < list.length; i++) {
            let product = list[i];
            if (!product.disabled) {
                product.checked = false;
                delete selected["product" + product.id];
            }
        }
        for (let i = 0; i < checked.length; i++) {
            let product = list[checked[i]];
            if (!product.disabled) {
                product.checked = true;
                selected["product" + product.id] = product;
            }
        }
        this.setData({
            selected: selected,
            selectedcount: Object.keys(selected).length,
            ["productlist." + tabindex + ".data"]: list
        });
    },
    //批量添加
    add_array: function () {
        var checked = [];
        var keys = Object.keys(this.data.selected);
        for (let i = 0; i < keys.length; i++) {
            let key = keys[i];
            let item = this.data.selected[key];
            let price =  item['ship_fare_type'] == 1 ? item['max_price'] : item.price;
            checked.push({
                id: item.id,
                pro_id: item.id,
                brand: item.brand,
                title: item.name,
                image: item['pic_big'],
                name:  item.name,
                price: price,
                range: item.province,
                description: item.intro,

                level:item.level,
                onsale:item.onsale,
                sprice:`￥${item.sprice}`,
                sprice1:item.sprice,
                orange:item.range,
                province:item.province,
                ship_time:item.ship_time,
                certification:item.certification,
                brandinfo:item.brandinfo,
            });
        }
        // console.log(checked);
        this.addshop(checked);
    },
    addshop: function (checked) {
        if (checked.length == 0) {
            app.func.toastPromise('请先选择商品')
        } else {
            let data = {
                minprice:this.data.minprice,
                maxprice:this.data.maxprice,
                checked:checked,
            };
            var cardid = this.data.cardid;
            if (cardid == 'null') {
                this.addpro(data);
            } else {
                this.selfaddpro(cardid, checked);
            }
        }
    },
    addpro: function (checked) {
        if(this.eventChannel != null) {
            this.eventChannel.emit('addProduct', checked);
        } else {
            app.func.setModalResult(checked);
        }
        wx.navigateBack({delta: 1,})
    },
    selfaddpro: function (cardid, checked) {
        let minprice = this.data.minprice;
        let maxprice = this.data.maxprice;
        let pages = getCurrentPages();
        let prevPage = pages[pages.length - 2];
        prevPage.setData({addpro: checked, modifyindex: 1, });
        wx.navigateBack({delta: 1,})
    },







    //左下角筛选价格
    hideApcancel:function(){
        this.setData({
            showPriceArea:false
        });
    },
    priceAreaTips:function(){
       this.setData({
           showPriceArea: !this.data.showPriceArea
       });
    },
    formsubmitPrice:function(e){
        let minprice = e.detail.value.minprice;
        let maxprice = e.detail.value.maxprice;
        if(minprice < 0 || minprice.length == 0){
            app.func.toastPromise('最小价格不符合规范');
            return;
        }
        if(maxprice < 0 || maxprice.length == 0){
            app.func.toastPromise('最大价格不符合规范');
            return;
        }
        if(parseInt(maxprice) < parseInt(minprice)){
            app.func.toastPromise('最大价格不能小于最小价格');
            return;
        }
        this.setData({
            minprice:minprice,
            maxprice:maxprice
        },()=>{
            this.fristdata();
        });
    },
    fristdata(){
        this.setData({
            showPriceArea:false
        });
        let data = this.data;
        if(data.id == 999){
            // nothing
        }else{
            let result =  this.packageJson( {
                id: data.id,
                key: data.key || '',
                sort: data.sort || '',
                minrate: data.minrate || '',
                maxrate: data.maxrate || '',
                brand:data.brand || '',
            });
            this.reqpropuct1(result);
        }
    },





    //跳转
    product_info: function (e) {
        var id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: '/pages/index/productdetail/product-description/product-description?id=' + id
        })
    },
    productdetail: function (e) {
        var id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: `/pages/index/productdetail/productdetail?id=${id}&hiddenbottom=1`
        })
    },
    login: function () {
        wx.navigateTo({
            url: '/pages/auth/auth'
        })
    },





});















